package 哈希表.赎金信;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/1/13 21:35
 * @description:给你两个字符串：ransomNote 和 magazine ，判断 ransomNote 能不能由 magazine 里面的字符构成
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        System.out.println(canConstruct("aa", "ab"));
    }

    //采用hashMap
    public static boolean canConstruct(String ransomNote, String magazine) {
        if (ransomNote.length() > magazine.length()){
            return false;
        }
        Map<Character,Integer> map = new HashMap<>();
        for (int i = 0; i < magazine.length(); i++) {
            map.put(magazine.charAt(i),map.getOrDefault(magazine.charAt(i),0)+1);
        }
        for (int i = 0; i < ransomNote.length(); i++) {
            if (map.containsKey(ransomNote.charAt(i))){
                int num = map.get(ransomNote.charAt(i));
                if (num <= 0){
                    return false;
                }else {
                    map.put(ransomNote.charAt(i),--num);
                }
            }else {
                return false;
            }
        }
        return true;
    }


    public static boolean test(String ransomNote ,String magazine) {
        if (magazine.length() < ransomNote.length()) {
            return false;
        }
        Map<Character,Integer> map = new HashMap<>();
        for (int i = 0; i < ransomNote.length(); i++) {
            map.put(ransomNote.charAt(i),map.getOrDefault(ransomNote.charAt(i),0)+1);
        }
        for (int i = 0; i < magazine.length(); i++) {
            char tmp = magazine.charAt(i);
            if (map.get(tmp) != null) {
                int integer = map.get(tmp);
                if (integer == 0) {
                    return false;
                } else {
                    map.put(tmp,--integer);
                }
            }else {
                return false;
            }
        }
        return true;
    }


}
